//
//  HEAddHealthReportViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/18.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEAddHealthReportViewController.h"
#import "HEAddPhotoCell.h"
#import "HEReportInputCell.h"
#import "HEReportTextCell.h"
#import "HEOrderTitleCell.h"
#import "HEAfterPhotoCell.h"
#import "HEDoctorServerComfireViewController.h"
#import "HEHealthReportModel.h"
#import "HEOneCategViewController.h"

@interface HEAddHealthReportViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) UIButton *bottomView;

@property (nonatomic, strong) UILabel *surplusLb;
@property (nonatomic, assign) NSInteger surplusNumb;
@property (nonatomic, strong) UIButton *goBuyBtn;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;

@end

@implementation HEAddHealthReportViewController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (_showSurplus) {
        [self loadRead];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"添加报告";
    
    _surplusNumb = 0;
    
    [self initUI];
    [self initCell];
    [self initTabBarView];
    
    if (_showSurplus) {
        [self initSurplus];
    }
}

- (void)initUI {
   CGFloat tabbarHeight = 49 + KSafeTabbarHeight;
   _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight- ZXNavBarHeight - tabbarHeight) style:UITableViewStylePlain];
   _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   _tableView.scrollsToTop = YES;
   _tableView.tableFooterView = [[UIView alloc] init];
   
   self.tableView.backgroundColor = KWhiteColor;
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
   [self.view addSubview:self.tableView];
}

- (void)initCell {
   // 总段
   _sections = [NSMutableArray array];
   NSMutableArray *classArr = [NSMutableArray array];
    

    self.formModel.rp_text = @"您不仅可以上传体检报告，也可以上传化验单或其它检测报告，我们的医生都会为您进行专业的解读服务，最多上传9张图片";

   // 添加报告照片
    GDFiterCellModel *addTitlModel = [GDFiterCellModel new];
    addTitlModel.cellKlass = HEOrderTitleCell.class;
    addTitlModel.leftTitle = @"添加报告照片";
    
    // 上传照片
     GDFiterCellModel *photoModel = [GDFiterCellModel new];
    photoModel.cellKlass = HEAddPhotoCell.class;
    photoModel.leftTitle = @"添加报告照片";
    photoModel.cellType = GDFiterCellTypeSelect_ADDPHOTO;
    photoModel.cellHeight = 108;
   
    //  
    GDFiterCellModel *noticeModel = [GDFiterCellModel new];
    noticeModel.cellKlass = HEReportTextCell.class;
    noticeModel.tableKey = @"rp_text";

    
    // 指导主体
     GDFiterCellModel *themModel = [GDFiterCellModel new];
    themModel.cellKlass = HEOrderTitleCell.class;
    themModel.leftTitle = @"指导主体";
   
   //
    GDFiterCellModel *inputModel = [GDFiterCellModel new];
    inputModel.cellKlass = HEReportInputCell.class;
    inputModel.placeHolder = @"为本次指导输入一个主题，方便以后查看";
    inputModel.tableKey = @"rp_title";

   // 添加的时候注意顺序，暂未对顺序做处理
   classArr = @[addTitlModel, photoModel, noticeModel, themModel, inputModel].mutableCopy;
   [self.tableView mc_registerCellByFiterModels:classArr];

   for (GDFiterCellModel *model in classArr) {
        NSMutableArray *secs = [NSMutableArray array];
        
       // 隐藏未达到条件的cell
        if (model.cellDisplayType == GDCellDisplayNone) {
            continue;
        }
        else if (model.cellType == GDFiterCellTypeOrderPay) {
        }
        else {
           [secs addObject:model];
       }
        
       [_sections addObject: secs];
    }
   
   [_tableView reloadData];
}

- (void)initTabBarView {
    UIButton *bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomView = bottomView;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = CNavBgColor;
    _bottomView.titleLabel.font = DYBlodFont(18);
    [bottomView setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [bottomView addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView setTitle: @"完成" forState:UIControlStateNormal];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(49);
        make.bottom.offset(-ZXSafeAreaBottom);
    }];
}

- (void)submit {
    
    if (_showSurplus) {
        if (_surplusNumb == 0) {
            [Dialog toastBottom:@"健康指导可用次数不足，请购买"];
            return;
        }
    }
    
    if (self.formModel.cm_imgs.count == 0) {
        [Dialog toastBottom:@"请添加相关报告照片!"];
        return;
    }
    
    if ([DYTools isBlankString:self.formModel.rp_title]) {
        [Dialog toastBottom:@"请输入指导主题"];
        return;
    }
     
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        self.group = dispatch_group_create();
        
        // 上传图片
        [self uploadImage: self.formModel];
        
        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(self.group, queue, ^{
            [self createSubmitRequest];
        });
    });
}

- (void)createSubmitRequest {
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:self.formModel.rp_title forKey:@"report_name"];
    if (_showSurplus) {
        [params setValue:@0 forKey:@"status"];
    }else {
        [params setValue:@4 forKey:@"status"]; // 找医生传报告，加上订单状态->待支付
        [params setValue:_userModel.user_id forKey:@"doc_id"];
    }
    [params setValue:[self.formModel.cm_imgUrls componentsJoinedByString:@","] forKey:@"report_url"];
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KsaveReport parameters: params success:^(id  _Nonnull responseObject) {

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        HEHealthReportModel *model = [HEHealthReportModel mj_objectWithKeyValues:response.data];
        
        if (response.success) {
            if (self.showSurplus) {
                [WOAlert alertShowTitle:@"" message:@"上传成功，医生回复后我们会为您推送消息，或您可以主动前往我的-健康指导中查看" cancelButtonTitle:@"知道了" otherButtonTitles:nil block:^(NSInteger buttonIndex) {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }else {
                HEDoctorServerComfireViewController *vc = [HEDoctorServerComfireViewController new];
                HEServerComfireModel *comfireModel = [HEServerComfireModel new];
                comfireModel.icon_url = self.userModel.avatar;
                comfireModel.topStr = self.userModel.realname;
                comfireModel.middleStr = self.userModel.KDeptStr;
                comfireModel.bottomStr = self.userModel.hospital_name;
                comfireModel.payParams = @[self.selectServerModel.server_name,
                                           [NSString stringWithFormat:@"￥%@%@", [NSDecimalNumber rounding:self.selectServerModel.price afterPoint:2], self.selectServerModel.unit]];
                
                
                HECreateOrderRequest *request = [HECreateOrderRequest new];
                request.orderType = HEOrderTypeGeneral;
                request.doctor_id = self.userModel.user_id;
                request.total = 1;
                request.goodsId = self.selectServerModel.goods_id;
                request.channel = self.selectServerModel.channel;
                request.skuId = self.selectServerModel.attr_id;
                request.source = HEOrderSourceTypeiOS;
                request.type = HESubmitPreviewTypeByGoodsDetails;
                request.appSource = KAppSource;
            
                HEExtraDoctorInfoModel *extra = [HEExtraDoctorInfoModel new];
                extra.planId = model.id;
                extra.order_type = self.selectServerModel.channel;
            
                extra.doctor_info = [DoctorInfo new];
                extra.doctor_info.user_id = self.userModel.user_id;
                extra.doctor_info.post_name = self.userModel.post_name;
                extra.doctor_info.avatar = self.userModel.avatar;
                extra.doctor_info.depart_name = self.userModel.depart_name;
                extra.doctor_info.realname = self.userModel.realname;
                request.extras = [extra mj_JSONString];
                
                vc.comfireModel = comfireModel;
                vc.orderRequest = request;
                vc.price = self.selectServerModel.price;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)uploadImage:(GDFormModel *)model {
    dispatch_group_enter(_group);
    model.cm_imgUrls = @[].mutableCopy;

    if (!(model.cm_imgs.count > 0)) {
        dispatch_group_leave(self.group);
        return;
    }
    
    [WOAFNetWorkingHandle uploadImagesWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil images:model.cm_imgs fileNames:nil imageScale:0.8 imageType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        

    } success:^(id  _Nonnull responseObject) {
        
        HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];

        NSArray *array = [response.data.src componentsSeparatedByString:@","];
        for (NSString *url in array) {
            if (![DYTools isBlankString:url]) {
                [model.cm_imgUrls addObject:url];
            }
        }
        dispatch_group_leave(self.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(self.group);
    }];
}

#pragma mark -
- (void)initSurplus {
    
    _surplusLb = [UILabel new];
    _surplusLb.font = DYBlodFont(16);
    _surplusLb.text = @"剩余次数：0";
    _surplusLb.textColor = CPriceColor;
    [self.view addSubview:_surplusLb];
    
    [_surplusLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).mas_offset(15);
        make.bottom.equalTo(self.view).mas_offset(-70);
        make.height.mas_offset(30);
    }];
    
    _goBuyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _goBuyBtn.titleLabel.font = DYBlodFont(16);
    [_goBuyBtn setTitle:@"立即购买" forState:UIControlStateNormal];
    [_goBuyBtn setTitleColor:CNavBgColor forState:UIControlStateNormal];
    _goBuyBtn.layer.borderColor = CNavBgColor.CGColor;
    _goBuyBtn.layer.borderWidth = 1;
    _goBuyBtn.layer.cornerRadius = 6;
    [self.view addSubview:_goBuyBtn];
    [_goBuyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_surplusLb.mas_right).offset(15);
        make.centerY.equalTo(_surplusLb);
        make.height.mas_offset(30);
        make.width.mas_offset(100);
    }];
    [_goBuyBtn addTarget:self action:@selector(toShopClick) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)toShopClick {
    HEOneCategViewController *vc = [HEOneCategViewController new];
    vc.categID = 1036026;
    vc.title = @"健康服务";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)loadRead {
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KuserGuideCnt parameters:@{} success:^(id  _Nonnull responseObject) {

        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        self.surplusNumb = response.data.integerValue;
        
        if (response.success) {
            if (self.surplusNumb > 0) {
                self.goBuyBtn.hidden = YES;
            }else {
                self.goBuyBtn.hidden = NO;
            }
            self.surplusLb.text = [NSString stringWithFormat:@"剩余次数：%@", response.data];
        }

    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   NSMutableArray *sec = _sections[section];
   return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSMutableArray *sec = _sections[indexPath.section];
   GDFiterCellModel *fiterModel = sec[indexPath.row];
   
   UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
   cell.selectionStyle = UITableViewCellSelectionStyleNone;
   fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
   return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  NSMutableArray *sec = _sections[indexPath.section];
   GDFiterCellModel *fiterModel = sec[indexPath.row];

    if (fiterModel.cellType == GDFiterCellTypeSelect_ADDPHOTO) {
        return fiterModel.cellHeight;
    }
   return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
              [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
   }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row]; 
}
 

#pragma mark - UITableViewDelegate
  
- (void)changeTabbarView {
 
}



@end
